<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\exception\LogicException;
use app\exam\model\admin\PaperConfig as PaperConfigModel;

/**
 * Class PaperConfig
 *
 * @package app\exam\logic\admin
 */
class PaperConfig extends PaperConfigModel
{

    /**
     * 设置
     *
     * @param string $dataKey
     * @param int    $paperId
     * @param array  $configData
     * @throws LogicException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveConfig(string $dataKey, int $paperId, array $configData)
    {
        $data = $this->where('paper_id', $paperId)
            ->where('data_key', $dataKey)
            ->find();
        if (!$data) {
            $saved = [
                'data_key' => $dataKey,
                'paper_id' => $paperId,
                'cnf_data' => $configData
            ];

            $ret = $this->create($saved);
        } else {
            $data->cnf_data = $configData;
            $ret            = $data->save();
        }

        if (!$ret) {
            throw new LogicException('设置失败');
        }
    }

    /**
     * 获取配置
     *
     * @param string $dataKey
     * @param int    $paperId
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get(string $dataKey, int $paperId)
    {
        $data = $this->where('paper_id', $paperId)
            ->where('data_key', $dataKey)
            ->find();

        return $data ? $data->cnf_data : [];
    }
}